package edu.seu.shuai.core;

import com.github.houbb.log.integration.core.Log;
import com.github.houbb.log.integration.core.LogFactory;
import edu.seu.shuai.api.IMQConsumer;
import edu.seu.shuai.api.IMQConsumerListener;
import edu.seu.shuai.constant.ConsumerConst;
import edu.seu.shuai.exception.MqException;
import edu.seu.shuai.handler.MQConsumerHandler;
import edu.seu.shuai.response.ConsumerRespCode;
import edu.seu.shuai.support.invoke.IInvokeService;
import edu.seu.shuai.utils.DelimiterUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;

public class MQConsumerPush extends Thread implements IMQConsumer {
    private static final Log log = LogFactory.getLog(MQConsumerPush.class);


    /**
     * 组名称
     */
    protected String groupName = ConsumerConst.DEFAULT_GROUP_NAME;

    /**
     * 调用管理类
     */
    private IInvokeService invokeService;


    /**
     * 中间人地址
     */
    protected String brokerAddress = "127.0.0.1:9999";

    /**
     * 分隔符
     */
    private String delimiter = DelimiterUtil.DELIMITER;

    protected int port = ConsumerConst.DEFAULT_PORT;

    @Override
    public void run() {
        // 启动服务端
        log.info("MQ 消费者开始启动服务端 groupName: {}, port: {}, brokerAddress: {}",
                groupName, port, brokerAddress);

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            final ByteBuf delimiterBuf = DelimiterUtil.getByteBuf(delimiter);

            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(workerGroup, bossGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel ch) throws Exception {
                            ch.pipeline()
                                    // 这里使用指定分隔符来解决粘包问题
                                    .addLast(new DelimiterBasedFrameDecoder(DelimiterUtil.LENGTH, delimiterBuf))
                                    .addLast(new MQConsumerHandler(invokeService));
                        }
                    })
                    // 这个参数影响的是还没有被accept 取出的连接
                    .option(ChannelOption.SO_BACKLOG, 128)
                    // 这个参数只是过一段时间内客户端没有响应，服务端会发送一个 ack 包，以判断客户端是否还活着。
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            // 绑定端口，开始接收进来的链接
            ChannelFuture channelFuture = serverBootstrap.bind(port).syncUninterruptibly();
            log.info("MQ 消费者启动完成，监听【" + port + "】端口");

            channelFuture.channel().closeFuture().syncUninterruptibly();
            log.info("MQ 消费者关闭完成");
        } catch (Exception e) {
            log.error("MQ 消费者启动异常", e);
            throw new MqException(ConsumerRespCode.RPC_INIT_FAILED);
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    @Override
    public void subscribe(String topicName, String tagRegex) {

    }

    @Override
    public void registerListener(IMQConsumerListener listener) {

    }


}
